package ink.onei.framework.web.service;

import ink.onei.common.core.domain.entity.Seller;
import ink.onei.common.core.domain.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * @Author: nekotako
 * @Description: TODO
 * @Date: 31/01/2024 11:27 Wednesday
 */

@Service
public class SellerAuthenticationProvider implements AuthenticationProvider {
    private static final Logger log = LoggerFactory.getLogger(SellerAuthenticationProvider.class);

    @Autowired
    private SellerDetailServiceImpl sellerDetailService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        // 这个获取表单输入中返回的用户名
        String username = authentication.getName();
        //这个获取表单输入中返回的密码
        String password = (String) authentication.getCredentials();

        UserDetails userDetails = sellerDetailService.loadUserByUsername(username);

        return new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());

        // 构建返回的用户登录成功的token
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }


    public UserDetails createLoginUser(Seller seller) {
        return new LoginUser(seller.getSellerId(), seller, permissionService.getMenuPermission(seller));
    }
}
